package com.wxg.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * Created by void on 2019/5/7.
 */
@RestController
@RequestMapping("/global")
public class GlobalRedisLockController {

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    private static final Logger logger = LoggerFactory.getLogger(GlobalRedisLockController.class);

    @GetMapping("/test2")
    public void test() throws InterruptedException{
        Lock lock = redisLockRegistry.obtain("lock");
        logger.info("global尝试加锁");
        boolean b1 = lock.tryLock(5, TimeUnit.SECONDS);
        logger.info("global加锁结果:{}", b1);

        TimeUnit.SECONDS.sleep(10);
        logger.info("global执行完业务代码,开始解锁");

        lock.unlock();
        logger.info("global解锁成功");
    }
}
